function getRoutes() {
  if (getRoutes.done) return getRoutes.result

  /* eslint-disable */
  const babel = require('@babel/core')
  const Path = require('path')
  const fs = require('fs')

  const log = (...args) => {console.log('[babel-plugin-router getRoutes]----------> ', ...args)}
  log('开始获取srm路由配置')

  const routesFPath = Path.resolve(__dirname, './src/router/srm/index.ts')
  const tmpFile = './srm-routes.tmp.js'

  let result = {}
  try {
    result = babel.transformFileSync(routesFPath, {babelrc: false, configFile: false,  presets: ['@babel/env', '@babel/typescript']})

  } catch(err) {
    log('babel转码routes.ts出错', err)
    return
  }

  const handleCode = (code) => {
    // window -> global
    code = code.replace(/\bwindow\b/mg, 'global')

    // (require('xxx')) -> ({})
    code = code.replace(/\(\s*require\([^\)]+\)\s*\)/gm, '({})')
    return code
  }
  
  const code = handleCode(result.code || '')

  fs.writeFileSync(tmpFile, code)

  let routes = []
  try {
    const allRoutes = require(tmpFile).default
    const srmRoot = allRoutes.find(r => r.name === 'srm')
    routes = srmRoot.children
    log('获取srm路由成功!')
    getRoutes.done = true
    getRoutes.result = routes
    process.env.routes = routes
  } catch(err) {
    log('解析routes出错', err)
  }

  fs.unlinkSync(tmpFile)

  return routes
}

function log(...args) {
  console.log('[fixRouterPlugin]========> ', ...args)
}

function fixRouterPlugin(babel, options, dirname) {
  return {
    visitor: {
      CallExpression(path, state) {
        const arg1 = path.node.arguments[0]
        const { callee } = path.node
        if (callee.type === 'MemberExpression' && callee.object.name) {
          if (callee.object.name.match(/router/i) && ['push', 'replace'].includes(callee.property.name)) {
            if (arg1.type !== 'ObjectExpression') {
              log(this.filename, 'router.push() 参数不是对象', path.node.arguments)
              return
            }

            const nameIndex = arg1.properties.findIndex((prop) => prop.key.name === 'name')
            const nameProp = arg1.properties[nameIndex]
            if (nameProp.value.type !== 'StringLiteral') {
              log(this.filename, 'router.push({name: var}) 参数对象的name 不是字符串直接量', nameProp)
              return
            }

            const nameVal = nameProp.value.value
            const targetRoute = options.routes.find((r) => r.name === nameVal)

            // del name prop
            arg1.properties.splice(nameIndex, 1) 
            
            // add path prop
            const realPath = targetRoute.path.match(/^\//) ? targetRoute.path : `/${targetRoute.path}`
            arg1.properties.push(babel.types.objectProperty(babel.types.stringLiteral('path'), babel.types.stringLiteral(realPath)))
          }
        }
      }

    }
  }
}

fixRouterPlugin.getRoutes = getRoutes

module.exports = fixRouterPlugin

